package com.tedu.openmedical.medicalsystem.base.shiroConfig;

import com.tedu.openmedical.medicalsystem.user.pojo.entity.User;
import com.tedu.openmedical.medicalsystem.user.pojo.vo.ActiveUser;
import com.tedu.openmedical.medicalsystem.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.codec.Hex;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

@Slf4j
public class DatabaseRealm extends AuthorizingRealm {

    @Autowired
    @Lazy
    private UserService userService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 获取身份验证信息
        log.debug("token:{}", token);
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        log.debug("upToken:{}", upToken);
        String username = upToken.getUsername();
        log.debug("username:{}", username);
        User user = getUserFromDatabase(username);
        log.debug("user:{}", user);
        if (user == null) {
            throw new UnknownAccountException("用户不存在");
        }
        String salt = user.getSalt();
        String password = user.getPassword();
        byte[] saltBytes = Hex.decode(salt);
        log.debug("salt:{}, password:{}", saltBytes, password);
        return new SimpleAuthenticationInfo(user,password, ByteSource.Util.bytes(saltBytes), getName());
    }



    private User getUserFromDatabase(String username) {
        // 模拟从数据库中获取用户信息
        return userService.findByUsername(username);
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        ActiveUser activeUser = (ActiveUser) principalCollection.getPrimaryPrincipal();
        return new SimpleAuthorizationInfo();
    }
}
